<template>
    <div class="users">
        <!-- 面包屑区域 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片区域 -->
        <el-card>
            <!-- 添加用户区域 -->
            <el-row :gutter="20">
                <el-col :span="10">
                    <el-input placeholder="请输入内容" 
                            v-model="queryInfo.query"
                            clearable
                            @clear='getUserList'>
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                    
                </el-col>
                <el-col :span="4">
                    <el-button type='primary' @click="addDialogVisible=true">添加用户</el-button>
                </el-col>
            </el-row>

            <!-- 表格区域 -->
            <el-table :data="userList" stripe border style="width: 100%">
                <el-table-column type='index'></el-table-column>
                <el-table-column label='姓名' prop="username"></el-table-column>
                <el-table-column label='邮箱' prop="email"></el-table-column>
                <el-table-column label='电话' prop="mobile"></el-table-column>
                <el-table-column label='角色' prop="role_name"></el-table-column>
                <el-table-column label='状态' prop="mg_state">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label='操作' width='180px'>
                    <template slot-scope="scope" >
                        <el-button type="primary" icon="el-icon-edit" size='mini' @click="editUser(scope.row.id)"></el-button>
                        <el-button type="danger" icon="el-icon-delete" size='mini' @click="removeById(scope.row.id)"></el-button>
                         <el-tooltip :enterable='false' effect="dark" content="分配权限" placement="top">
                            <el-button type="warning" icon="el-icon-setting" size='mini' @click="setRights(scope.row)"></el-button>
                        </el-tooltip>
                        
                    </template>
                </el-table-column>
            </el-table>

            <!-- 底部分页 -->
            <el-pagination @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="queryInfo.pagenum"
                        :page-sizes="[1, 2, 3, 5]"
                        :page-size="queryInfo.pagesize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
            </el-pagination>

            <!-- 添加用户区域 -->
            <el-dialog title="添加用户"
                        :visible.sync="addDialogVisible"
                        width="50%"
                         @close='closeDialogVisible'>
                <el-form :model="addForm" 
                        :rules="addFormRules" 
                        ref="addFormRef" 
                        label-width="80px">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="addForm.username"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="addForm.password"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="addForm.email"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号码" prop="mobile">
                        <el-input v-model="addForm.mobile"></el-input>
                    </el-form-item>
                    
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addUser">确 定</el-button>
                </span>
            </el-dialog>

            <!-- 修改用户 -->
            <el-dialog title="编辑用户"
                        :visible.sync="editDialogVisible"
                        width="50%"
                        @close='editDialogClose'>
                    <el-form ref="editFormRef" 
                            :model="editForm" 
                            :rules='editFormRule'
                            label-width="80px">
                        <el-form-item label="用户名称" >
                            <el-input v-model="editForm.username" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="邮箱" prop='email'>
                            <el-input v-model="editForm.email"></el-input>
                        </el-form-item>
                        <el-form-item label="手机号码" prop='mobile'>
                            <el-input v-model="editForm.mobile"></el-input>
                        </el-form-item>
                        
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="editDialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="editDialogShow">确 定</el-button>
                    </span>
            </el-dialog>

            <!-- 分配权限区域 -->
            <el-dialog title="提示"
                        :visible.sync="rightDialogVisible"
                        width="50%"
                        @close='roleDialogClosed'>
                <div>
                    <p>当前的用户：{{userInfo.username}}</p>
                    <p>当前的角色：{{userInfo.role_name}}</p>
                    <p>分配新角色：
                         <el-select v-model="selectRoleId" placeholder="请选择">
                            <el-option v-for="item in roleList"
                                        :key="item.id"
                                        :label="item.roleName"
                                        :value="item.id">
                            </el-option>
                        </el-select>
                    </p>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="rightDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveRole">确 定</el-button>
                </span>
                </el-dialog>
        </el-card>
 
    </div>
</template>

<script>
import { getUserList, getStateChange, addUser, getEditDialogShow, removeUserById } from 'network/query'
import request from 'network/query'
export default {
   name:'Users',
   data(){
       var checkEmail = (rule,value, callback) => {
            const regEmail = /^([a-zA-Z0-9_-]+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]))/
            if(regEmail.test(value)){
                return callback()
            }
            callback(new Error('请输入合法的邮箱！'))
        }
        var checkMobile = (rule,value,callback) => {
            const regMobile = /^(13[0-9]|15[0-35-9]|17[678]|18[0-9]|14[57])\d{8}$/
            if(regMobile.test(value)){
                return callback()
            }
            callback(new Error('请输入合法的手机号！'))
        }
       return {
           queryInfo:{
               query:'',
               pagenum:1,
               pagesize:3
           },
           userList:[],
           total:0,
        //    userinfo:{},
        //    uId:this.userinfo,
        //    type:this.userinfo,
           addDialogVisible:false,
           addForm:{
               username:'',
               password:'',
               email:'',
               mobile:''
           },
           addFormRules:{
               username:[
                   {required:true, message:'请输入用户名',trigger:'blur'},
                   {min:3,max:8,message:'长度在3-8个字符',trigger:'blur'}
               ],
               password:[
                   {required:true, message:'请输入密码',trigger:'blur'},
                   {min:6,max:10,message:'长度在6-10个字符',trigger:'blur'}
               ],
               email:[
                   {required:true, message:'请输入密码',trigger:'blur'},
                   {validator:checkEmail, trigger:'blur'}
                   
               ],
               mobile:[
                   {required:true, message:'请输入密码',trigger:'blur'},
                   {validator:checkMobile, trigger:'blur'}
               ]
           },
           editForm:{},
           editDialogVisible:false,
           editFormRule:{
               email:[
                   {required:true, message:'请输入用户邮箱',trigger:'blur'},
                   {validator:checkEmail, trigger:'blur'}
                   
               ],
               mobile:[
                   {required:true, message:'请输入用户手机号',trigger:'blur'},
                   {validator:checkMobile, trigger:'blur'}
               ]
           },
           rightDialogVisible:false,
           userInfo:{},
           roleList:[],
           selectRoleId:''
       }
   },
   created(){
       this.getUserList()
   },
   methods:{
    //    网络请求方法
    //    async getUserList(){
    //         const {data:res} = await this.$http.get('users',{params:this.queryInfo})
    //         if(res.meta.status !== 200){
    //             return this.$message.error('获取用户列表失败！')
    //         }
    //         this.userList = res.data.users,
    //         this.total = res.data.total
    //    },
       getUserList(){
           getUserList(this.queryInfo).then(res=>{
               console.log(res);
               if(res.meta.status !== 200){
                   return this.$message.error('获取用户列表失败！')
               }
               this.userList = res.data.users
               this.total = res.data.total
           })
       },

    //    async userStateChange(userinfo){
    //     //    const {data:res} = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
    //        const {data:res} = await this.$http.put('users/'+userinfo.id+'/state/'+userinfo.mg_state)
    //     //    const {data:res} = await this.$http.put('users/'+this.uId+'/state/'+this.type)

    //        console.log(res);
    //        if(res.meta.status !== 200){
    //            userinfo.mg_state = !userinfo.mg_state
    //            return this.$message.error('更改用户状态失败！')
    //        }
    //        this.$message.success('更改用户状态成功！')
    //    },

        userStateChange(userinfo){
            getStateChange(`users/${userinfo.id}/state/${userinfo.mg_state}`).then(res=>{
                // console.log(res);
                if(res.meta.status !== 200){
                    return this.$message.error('更改用户状态失败！')
                }
                 this.$message.success('更改用户状态成功！')
            })
        },

    //    事件监听方法
        handleSizeChange(newSize){
            // console.log(newSize);
            this.queryInfo.pagesize = newSize
            this.getUserList()
        },

        handleCurrentChange(newPage){
            // console.log(newPage);
            this.queryInfo.pagenum = newPage
            this.getUserList()
        },

        closeDialogVisible(){
            this.$refs.addFormRef.resetFields()
        },

        // 添加用户
        addUser(){
            this.$refs.addFormRef.validate(valid=>{
                if(!valid) return
                // addUser(this.addForm.username,this.addForm.password,this.addForm.email,this.addForm.mobile).then(res=>{
                //     console.log(res);
                //     this.userInfo = res.data
                //     this.getUserList()
                // })
                addUser(this.addForm).then(res=>{
                    console.log(res);
                    if(res.meta.status!==201){
                        return this.$message.error('添加用户失败！')
                    }
                    this.$message.success('添加用户成功~')
                })
                this.getUserList()
                this.addDialogVisible = false
                // const {data:res} = await this.$http.post('/users',this.addForm)
                // console.log(res);
            })
            
        },

        // 修改用户
        async editUser(id){
            const {data:res} = await this.$http.get('users/'+id)
            console.log(res);
            this.editForm = res.data
            this.editDialogVisible = true
        },

        editDialogClose(){
            this.$refs.editFormRef.resetFields()
        },

        editDialogShow(){
            this.$refs.editFormRef.validate(async valid=>{
                if(!valid) return
                // const {data:res} = await this.$http.put('users/'+this.editForm.id,{
                //     email:this.editForm.email,
                //     mobile:this.editForm.mobile
                // })
                // if(res.meta.status !== 200){
                //     return this.$message.error('修改用户失败！')
                // }

                getEditDialogShow('users/'+this.editForm.id,this.editForm.email,this.editForm.mobile).then(res=>{
                    console.log(res);
                    if(res.meta.status !== 200){
                        return this.$message.error('修改用户失败！')
                    }
                    this.$message.success('修改用户成功~')
                    this.getUserList()
                })
                
                // getEditDialogShow('users/'+this.editForm.id,{
                //     email:this.editForm.email,
                //     mobile:this.editForm.mobile
                // }).then(res=>{
                //     console.log(res);
                //     if(res.meta.status !== 200){
                //         return this.$message.error('修改用户失败！')
                //     }
                //     this.$message.success('修改用户成功~')
                //     this.getUserList()
                // })
                
            })
            this.editDialogVisible = false
        },

        // 删除用户
        async removeById(id){
            const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            if(confirmResult!=='confirm'){
                return this.$message.info('已取消删除')
            }
            // const {data:res} = await this.$http.delete('users/'+id)
            // console.log(res);
            // if(res.meta.status !== 200){
            //     return this.$message.error('删除用户失败！')
            // }
            // removeUserById('users/'+id).then(res=>{
            //     if(res.meta.status !== 200){
            //         return this.$message.error('删除用户失败！')
            //     }
            //     this.getUserList()
            // })

            request('users/'+id,{},{},'delete').then(res=>{
                console.log(res);
                    if(res.meta.status !== 200){
                        return this.$message.error('删除用户失败！')
                    }
                this.getUserList()
            })
            
            
            this.$message.success('删除用户成功！')
        },

        setRights(userInfo){
            this.userInfo = userInfo
            request('roles').then(res=>{
                console.log(res);
                if(res.meta.status !== 200){
                    this.$message.error('获取权限列表失败')
                }
                this.roleList = res.data
            })
            this.rightDialogVisible = true
        },

        saveRole(){
            console.log(123);
            if(!this.selectRoleId){
                this.$message.error('请选择要分配的角色')
            }
            request(`users/${this.userInfo.id}/role`,{},{
                rid:this.selectRoleId
            },'put').then(res=>{
                console.log(res);
                if(res.meta.status !== 200){
                    this.$message.error('更新用户角色失败！')
                }
                this.$message.success('更新用户角色成功~')
                this.getUserList()
            })
            this.rightDialogVisible = false
        },

        roleDialogClosed(){
            this.selectRoleId = ''
            this.userInfo = {}
        }

       
   }
};
</script>

<style scoped>

</style>
